<template>
  <el-dialog
    v-if="dialogShow"
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    custom-class="mydialog"
    width="600px"
    :title="titleContent"
    @close="close"
  >
    <el-form
      ref="formRef"
      class="myForm"
      :model="formData"
      :label-width="formLabelWidth"
      size="small"
      :rules="formRules"
    >
      <el-form-item
        class="form-item"
        label="选择地区"
        prop="area"
      >
        <el-cascader
          ref="cascader"
          v-model="formData.area"
          :popper-append-to-body="false"
          style="width: 100%;"
          :options="citys"
          placeholder="请选择适用地区"
          :props="{multiple: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode', disabled: 'disabled' }"
          collapse-tags
          clearable
          @change="areaChange"
        />
      </el-form-item>
      <!--
      <el-form-item
        class="form-item"
        label="市场进化属性"
        prop="maturity"
      >
        <el-select
          v-model="formData.maturity"
          style="width: 100%"
          clearable
          filterable
          placeholder="请选择市场进化属性"
        >
          <el-option
            v-for="(itm) in marketMaturity"
            :key="itm.id"
            :label="itm.label"
            :value="itm.value"
          />
        </el-select>
      </el-form-item>
      -->
      <el-form-item
        class="form-item"
        label="市场营销模式"
        prop="marketSellMode"
      >
        <el-checkbox-group v-model="formData.marketSellMode">
          <el-checkbox
            v-for="(itm) in marketSellModeOption"
            :key="itm.id"
            :label="itm.value"
          >{{ itm.label }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          style="margin-right: 20px;"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="save"
        >保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  inject,
  reactive,
  ref,
  toRefs,
} from 'vue'
import { crmStore } from '@CRM/store'
import { selectAreaTree } from '@/utils/areaFuc.js'
import { useRoute } from 'vue-router'

export default defineComponent({
  emits: ['refresh'],
  setup(props, context) {
    const api = inject('api')
    const route = useRoute()
    const currentInstance = getCurrentInstance()
    var formRef = ref(null)
    var cascader = ref(null)
    var formLabelWidth = ref(120)
    var dialogShow = ref(false)
    var datas = reactive({
      citys: [],
      dialogType: 'create',
      titleContent: '添加市场规则',
      formData: {
        id: 0,
        productId: Number(route.query.productId) || 0,
        area: '',
        region: [],
        maturity: '',
        marketSellMode: [],
      },
      marketMaturity:
        crmStore.getters['dictionary/getDictionary']['product_attribute'] || [],
      marketSellModeOption:
        crmStore.getters['dictionary/getDictionary']['market_sell_mode'] || [],
    })
    var formRules = reactive({
      area: [
        {
          required: true,
          message: '请选择地区',
          trigger: 'change',
        },
      ],
      maturity: [
        {
          required: false,
          message: '请选择市场进化属性',
          trigger: 'change',
        },
      ],
      marketSellMode: [
        {
          required: true,
          message: '请选择市场营销模式',
          trigger: 'change',
        },
      ],
    })
    const areaSelectCode = (objData) => {
      var selArr = []
      for (var i = 0; i < objData.areas.length; i++) {
        var item = [
          objData.provinceCode,
          objData.cityCode,
          objData.areas[i].regionCode,
        ]
        selArr.push(item)
      }
      console.log(selArr)
      return selArr
    }
    const reset = () => {
      datas.formData = {
        id: 0,
        productId: Number(route.query.productId) || 0,
        area: '',
        region: [],
        maturity: '',
        marketSellMode: [],
      }
    }
    // 获取省市区数据源--包含是否可用
    const getAreaList = (id) => {
      var data = { id: id, productId: datas.formData.productId }
      api.common.GET_AREA_LIST(data).then((res) => {
        if (res.code === 0) {
          console.log(res.data)
          datas.citys = res.data.region || []
        }
      })
    }
    const open = (data) => {
      console.log(data)
      datas.dialogType = data.types
      if (data.types === 'edit') {
        datas.formData.id = data.data.id
        datas.formData.area = areaSelectCode(data.data)
        datas.formData.maturity = data.data.maturity
        datas.formData.marketSellMode = data.data.marketSellMode
        console.log(datas.formData)
      }
      getAreaList(data?.data?.id || 0)
      dialogShow.value = true
    }
    const close = () => {
      reset()
      dialogShow.value = false
    }
    const areaChange = (val) => {
      console.log(datas.formData.region)
    }
    const create = () => {
      datas.formData.region = selectAreaTree(cascader.value.getCheckedNodes())
      api.marketRule
        .MARKET_RULE_CREATE(datas.formData)
        .then((res) => {
          console.log(res)
          if (res.code === 0) {
            currentInstance.proxy.customMessage({
              type: 'success',
              message: '创建成功',
            })
            context.emit('refresh')
            close()
          }
        })
        .catch((err) => {
          console.log(err)
        })
    }
    const edit = () => {
      datas.formData.region = selectAreaTree(cascader.value.getCheckedNodes())
      api.marketRule
        .MARKET_RULE_EDIT(datas.formData)
        .then((res) => {
          console.log(res)
          if (res.code === 0) {
            currentInstance.proxy.customMessage({
              type: 'success',
              message: '编辑成功',
            })
            context.emit('refresh')
            close()
          }
        })
        .catch((err) => {
          console.log(err)
        })
    }
    const save = () => {
      console.log(datas.formData)
      formRef.value.validate((valid) => {
        if (valid) {
          if (datas.dialogType === 'create') {
            create()
          } else if (datas.dialogType === 'edit') {
            edit()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }

    return {
      formRef,
      cascader,
      formLabelWidth,
      dialogShow,
      ...toRefs(datas),
      formRules,
      save,
      close,
      open,
      areaChange,
    }
  },
})
</script>
